use image::{imageops::FilterType, GenericImageView};
///windows cmd默认不支持 ansi 转义序列 但是在cmd使用cargo run 运行转义序列生效.原因如下.<br>
/// https://github.com/rust-lang/cargo/blob/0506d8d5c9dd229c94641dd39a37bd947dc0a770/src/cargo/core/shell.rs#L330
fn main() -> Result<(), Box<dyn std::error::Error>> {
    if cfg!(windows){
        pub fn enable_virtual_terminal_processing() {
            use winapi_util::console::Console;

            if let Ok(mut term) = Console::stdout() {
                let _ = term.set_virtual_terminal_processing(true);
            }
            if let Ok(mut term) = Console::stderr() {
                let _ = term.set_virtual_terminal_processing(true);
            }
        }
        enable_virtual_terminal_processing();
    }
    let img_path = "d:/AIGC/cat.png"; // 圖片路徑
    let caption = "圖片標題";         // 顯示在圖片下方的文字

    // 加載圖片
    let img = image::open(img_path)?;
    let (img_width, img_height) = img.dimensions();
    println!("img_width {img_width} img_height {img_height}");
    // 獲取終端尺寸
    let (term_cols, term_rows) = term_size::dimensions().unwrap_or((80, 24));
    println!("term_cols {term_cols} term_rows {term_rows}");
    let max_width = term_cols as u32;
    // 保留一行顯示文字，因此可用行數為 term_rows - 1
    let max_height = 2 * (term_rows.saturating_sub(1)) as u32; // 每行顯示兩像素

    // 計算調整後的圖片尺寸（保持寬高比）
    let (target_width, target_height) = {
        let aspect_ratio = img_width as f32 / img_height as f32;
        let mut width = max_width;
        let mut height = (width as f32 / aspect_ratio) as u32;

        if height > max_height {
            height = max_height;
            width = (height as f32 * aspect_ratio) as u32;
        }
        (width, height)
    };
    println!("target width {target_width} target height {target_height}");
    // 調整圖片大小
    let resized_img = img.resize_exact(target_width, target_height, FilterType::Triangle);
    let rgb_img = resized_img.to_rgb8();

    // 生成ANSI字符串
    let mut output = String::new();
    for y in 0..target_height / 2 {
        let y_top = y * 2;
        let y_bottom = y_top + 1;

        for x in 0..target_width {
            // 獲取上下兩個像素
            let pixel_top = rgb_img.get_pixel(x, y_top);
            let pixel_bottom = if y_bottom < target_height {
                rgb_img.get_pixel(x, y_bottom)
            } else {
                &image::Rgb([0, 0, 0]) // 最後一行補黑
            };

            // 轉換為ANSI顏色代碼
            output.push_str(&format!(
                "\x1b[38;2;{};{};{};48;2;{};{};{}m▀",
                // "\x1b[38;2;{};{};{};48;2;{};{};{}m ",
                pixel_top[0], pixel_top[1], pixel_top[2],
                pixel_bottom[0], pixel_bottom[1], pixel_bottom[2]
            ));
        }
        output.push_str("\x1b[0m\n"); // 重置顏色並換行
    }

    // 輸出圖片和文字
    println!("{}", output);
    println!("\x1b[0m{}", caption); // 確保文字顏色重置

    Ok(())
}
